package com.william.lifetraxer.utils;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.LiveFolders;
import android.text.TextUtils;

public class TrackContentProvider extends ContentProvider {
	
	private DbOpenHelper mDbOpenHelper ;
	
	private static HashMap<String,String> projectionMap ;
	private static HashMap<String,String> liveFolderProjectionMap ;
	
	private final static int ITEM = 1;
	private final static int COLLECTION = 2;
	private final static int LIVE_FOLDER = 3;
	
	private final static UriMatcher mUriMatcher ;
	
	static{
		
		mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		mUriMatcher.addURI(TrackDb.AUTHORITY, "tracks", COLLECTION);
		mUriMatcher.addURI(TrackDb.AUTHORITY, "tracks/#", ITEM);
		mUriMatcher.addURI(TrackDb.AUTHORITY, "track_live_folder", LIVE_FOLDER);
		
		projectionMap = new HashMap<String,String>();
		projectionMap.put(TrackDb.TrackColumns._ID, TrackDb.TrackColumns._ID);
		projectionMap.put(TrackDb.TrackColumns.TRACK_ID, TrackDb.TrackColumns.TRACK_ID);
		projectionMap.put(TrackDb.TrackColumns.USER_ID, TrackDb.TrackColumns.USER_ID);
		projectionMap.put(TrackDb.TrackColumns.GROUP_ID, TrackDb.TrackColumns.GROUP_ID);
		projectionMap.put(TrackDb.TrackColumns.PATH, TrackDb.TrackColumns.PATH);
		projectionMap.put(TrackDb.TrackColumns.NAME, TrackDb.TrackColumns.NAME);
		
		liveFolderProjectionMap = new HashMap<String,String>();
		liveFolderProjectionMap.put(LiveFolders._ID, TrackDb.TrackColumns._ID + " AS " + LiveFolders._ID);
		liveFolderProjectionMap.put(LiveFolders.NAME, TrackDb.TrackColumns.NAME + " AS " + LiveFolders.NAME);
		
	}

	@Override
	public boolean onCreate() {
		mDbOpenHelper = new DbOpenHelper(this.getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(TrackDb.TABLE_NAME);
		
		switch(mUriMatcher.match(uri)){
		case ITEM:
			qb.setProjectionMap(projectionMap);
			qb.appendWhere(TrackDb.TrackColumns._ID + " = " + uri.getPathSegments().get(1));
			break;
		case COLLECTION:
			qb.setProjectionMap(projectionMap);
			break;
		case LIVE_FOLDER:
			qb.setProjectionMap(liveFolderProjectionMap);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		
		String orderBy ;
		if(sortOrder!=null){
			orderBy=sortOrder;
		}else{
			orderBy=TrackDb.DEFAULT_SORT_ORDER;
		}
		
		SQLiteDatabase db = mDbOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
        c.setNotificationUri(getContext().getContentResolver(), uri);
		
		return c;
	}

	@Override
	public String getType(Uri uri) {
		switch (mUriMatcher.match(uri)) {
		case ITEM:
        	return TrackDb.ITEM_TYPE;
        case COLLECTION:
            return TrackDb.COLLECTION_TYPE;
        case LIVE_FOLDER:
            return TrackDb.COLLECTION_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		if (mUriMatcher.match(uri) != COLLECTION) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
		
		ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
        	throw new SQLException("Failed to insert row into " + uri);
        }

        SQLiteDatabase db = mDbOpenHelper.getWritableDatabase();
        long rowId = db.insert(TrackDb.TABLE_NAME, TrackDb.TrackColumns.TRACK_ID , values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(TrackDb.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		 SQLiteDatabase db = mDbOpenHelper.getWritableDatabase();
	        int count;
	        switch (mUriMatcher.match(uri)) {
	        case ITEM:
	            count = db.delete(TrackDb.TABLE_NAME, selection, selectionArgs);
	            break;

	        case COLLECTION:
	            String noteId = uri.getPathSegments().get(1);
	            count = db.delete(TrackDb.TABLE_NAME, TrackDb.TrackColumns._ID + " = " + noteId
	                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
	            break;

	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		 SQLiteDatabase db = mDbOpenHelper.getWritableDatabase();
	        int count;
	        switch (mUriMatcher.match(uri)) {
	        case COLLECTION:
	            count = db.update(TrackDb.TABLE_NAME, values, selection, selectionArgs);
	            break;
	        case ITEM:
	            String noteId = uri.getPathSegments().get(1);
	            count = db.update(TrackDb.TABLE_NAME, values, TrackDb.TrackColumns._ID + "=" + noteId
	                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
	            break;
	        default:
	            throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	}

}
